package com.hj.ct.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.hj.ct.db.DBConstants;
import com.hj.ct.parse.Device;

public class DeviceDao extends SQLBaseDao {

	public DeviceDao(Context context) {
		super(context);
	}

	/**
	 * 插入数据
	 * 
	 * @param message
	 */
	public void insertDevices(List<Device> devices) {
		db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		for (int i = 0; i < devices.size(); i++) {
			ContentValues values = getCV(devices.get(i));
			db.insert(DBConstants.SQL_DEVICE_TABLE, null, values);
		}
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}

	public ContentValues getCV(Device device) {
		ContentValues values = new ContentValues();
		values.put("deviceID", device.getDeviceID());
		values.put("deviceName", device.getDeviceName());
		values.put("deviceDesc", device.getDeviceDesc());
		values.put("latitude", device.getLatitude());
		values.put("longitude", device.getLongitude());
		values.put("img", device.getImg());
		return values;
	}

	/**
	 * 删除数据
	 * 
	 * @param message
	 */
	public void deleteDevices() {
		db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		db.delete(DBConstants.SQL_DEVICE_TABLE, null, null);
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}

	public List<Device> getDevices() {
		db = dbHelper.getReadableDatabase();
		List<Device> devieces = new ArrayList<Device>();
		Cursor cursor = db.query(DBConstants.SQL_DEVICE_TABLE, null, null, null, null, null, "id asc");
		while (cursor.moveToNext()) {
			Device device = new Device();
			device.setDeviceID(cursor.getString(cursor.getColumnIndex("deviceID")));
			device.setDeviceName(cursor.getString(cursor.getColumnIndex("deviceName")));
			device.setDeviceDesc(cursor.getString(cursor.getColumnIndex("deviceDesc")));
			device.setLatitude(cursor.getDouble(cursor.getColumnIndex("latitude")));
			device.setLongitude(cursor.getDouble(cursor.getColumnIndex("longitude")));
			device.setImg(cursor.getString(cursor.getColumnIndex("img")));
			devieces.add(device);
		}
		db.close();
		return devieces;
	}
}
